package com.party.mobile.web.controller.competition;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.competition.*;
import com.party.core.model.member.Member;
import com.party.core.model.system.TargetType;
import com.party.core.service.competition.*;
import com.party.core.service.competition.biz.CompetitionResultBizService;
import com.party.core.service.member.IMemberService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.annotation.VisitCollect;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.competition.input.RankInput;
import com.party.mobile.web.dto.competition.output.CompetitionMemberOutput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 参赛人员成绩
 *
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/competition/result")
public class CompetitionResultController {
	@Autowired
	private ICompetitionProjectService competitionProjectService;
	@Autowired
	private ICompetitionScheduleService competitionScheduleService;
	@Autowired
	private CurrentUserBizService currentUserBizService;
	@Autowired
	private CompetitionResultBizService competitionResultBizService;
	@Autowired
	private ICompetitionMemberService competitionMemberService;
	@Autowired
	private ICompetitionResultService competitionResultService;
	@Autowired
	private ICompetitionGroupResultService competitionGroupResultService;
	@Autowired
	private ICompetitionGroupService competitionGroupService;
	@Autowired
	private IMemberService memberService;

	Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 项目列表
	 *
	 * @param project
	 * @param page
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/list")
	public AjaxResult list(CompetitionProject project, Page page, HttpServletRequest request) {
		CurrentUser curUser = currentUserBizService.getCurrentUser(request);
		project.setCreateBy(curUser.getId());
		List<CompetitionProject> projects = competitionProjectService.listPage(project, page);
		return AjaxResult.success(projects, page);
	}

	/**
	 * 个人的所有成绩
	 *
	 * @param projectId
	 * @param cMemberId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getPersonalResult")
	public AjaxResult getPersonalResult(String projectId, String cMemberId, Page page) {
		List<CompetitionSchedule> joinedSchedules = competitionScheduleService.list(new CompetitionSchedule(projectId, YesNoStatus.YES.getCode()));
		List<Map<String, Object>> joinedData = competitionResultBizService.getPersonResult(projectId, cMemberId, joinedSchedules);

		List<CompetitionSchedule> canceledSchedules = competitionScheduleService.list(new CompetitionSchedule(projectId, YesNoStatus.NO.getCode()));
		List<Map<String, Object>> cancaledData = competitionResultBizService.getPersonResult(projectId, cMemberId, canceledSchedules);

		Map<String, Object> results = Maps.newHashMap();
		results.put("joinedData", joinedData);
		results.put("cancaledData", cancaledData);
		return AjaxResult.success(results);
	}

    /**
     * 个人成绩
     *
     * @param projectId  项目编号
     * @param memberId   用户编号
     * @param scheduleId 赛程编号
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/getPersonalDetail")
	@VisitCollect(module = TargetType.COMPETITION)
    public AjaxResult getPersonalDetail(String projectId, String memberId, String scheduleId, HttpServletRequest request) {
        if (StringUtils.isEmpty(projectId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
        }
        try {
            if (StringUtils.isEmpty(memberId)) {
                CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
                memberId = currentUser.getId();
            }
			CompetitionMember cMember = competitionMemberService.findByProjectAndMember(memberId, projectId);
			if (cMember == null) {
                return AjaxResult.error(PartyCode.DATA_UNEXIST, "您还没有参加比赛");
            }
			CompetitionMemberOutput memberOutput = new CompetitionMemberOutput();
			memberOutput.setNumber(cMember.getNumber());
			memberOutput.setCmemberId(cMember.getId());
			memberOutput.setMemberId(memberId);

			// 用户
			Member member = memberService.get(memberId);
			memberOutput.setFullName(member.getFullname());
			memberOutput.setRealName(member.getRealname());
            memberOutput.setSex(member.getSex());

			memberOutput.setProjectId(projectId);
			CompetitionProject cProject = competitionProjectService.get(projectId);
			if (cProject != null) {
                memberOutput.setProjectName(cProject.getTitle());
                memberOutput.setProjectRemarks(cProject.getRemarks());
                memberOutput.setProjectPicture(cProject.getPicture());
            }

            Integer openStatus = YesNoStatus.YES.getCode();
            if (StringUtils.isNotEmpty(scheduleId)) {
                openStatus = YesNoStatus.NO.getCode();
            }

            List<CompetitionResult> results = competitionResultService.findByMemberId(cMember.getId(), openStatus, scheduleId);
            if (results.size() > 0) {
                Double totalResult = 0d;
                Double totalDistance = 0d;
                for (CompetitionResult result : results) {
                    String actualRange = result.getActualRange();
                    String secondsResult = result.getSecondsResult();

                    totalResult = BigDecimalUtils.add(totalResult, Double.parseDouble(secondsResult));
                    totalDistance = BigDecimalUtils.add(totalDistance, Double.parseDouble(actualRange));
                }

                if (totalResult != null) {
                    double avgSecondsResult = BigDecimalUtils.div(totalResult, results.size());
                    String avgResult = competitionResultBizService.getResult(avgSecondsResult);
                    memberOutput.setAvgResult(avgResult);

                    String result = competitionResultBizService.getResult(totalResult);
                    memberOutput.setTotalSecondsResult(result);
                }
                if (totalDistance != null) {
                    Double ss = BigDecimalUtils.round(totalDistance, 1);
                    memberOutput.setTotalDistance(ss.toString());
                }

                // 总排行第几
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("projectId", projectId);
//                params.put("isComplete", "1");
                params.put("openStatus", openStatus);
                params.put("memberId", memberId);
                params.put("scheduleId", scheduleId);
                List<Map<String, Object>> memberResults = competitionResultService.getAllResult(params, null);
                competitionResultBizService.getMemberResultRank(memberResults, projectId, "");
                if (memberResults.size() > 0) {
                    String rowno = memberResults.get(0).get("rowno").toString();
					logger.info("总排名：{}", rowno);
                    memberOutput.setMemberRank(Double.valueOf(rowno).intValue());
                }

                if (member.getSex() != null) {
                    // 男子或女子排行
                    params = new HashMap<String, Object>();
                    params.put("projectId", projectId);
//                    params.put("isComplete", "1");
                    params.put("openStatus", openStatus);
                    params.put("memberId", memberId);
                    params.put("scheduleId", scheduleId);
                    params.put("sex", member.getSex());
                    memberResults = competitionResultService.getAllResult(params, null);
                    competitionResultBizService.getMemberResultRank(memberResults, projectId, "");
                    if (memberResults.size() > 0) {
                        String rowno = memberResults.get(0).get("rowno").toString();
						logger.info("男子或女子排名：{}", rowno);
                        memberOutput.setMemberSexRank(Double.valueOf(rowno).intValue());
                    }
                }
            }

			// 小组排行第几
			if (StringUtils.isNotEmpty(cMember.getGroupId())) {
                CompetitionGroup group = competitionGroupService.get(cMember.getGroupId());
                memberOutput.setGroupName(group.getGroupName());

                Map<String, Object> params = new HashMap<String, Object>();
                params.put("projectId", projectId);
//                params.put("isComplete", "1");
                params.put("memberId", memberId);
                params.put("groupId", cMember.getGroupId());
                params.put("scheduleId", scheduleId);
                List<Map<String, Object>> groupMemberResults = competitionResultService.getGroupAllPersonResult(params, null);
                competitionResultBizService.getMemberResultRank(groupMemberResults, projectId, "");
                if (groupMemberResults.size() > 0) {
                    String rowno = groupMemberResults.get(0).get("rowno").toString();
                    logger.info("小组排名：{}", rowno);
                    memberOutput.setGroupMemberRank(Double.valueOf(rowno).intValue());
                }
            }
			return AjaxResult.success(memberOutput);
		} catch (Exception e) {
			logger.error("获取个人详情异常", e);
			return AjaxResult.error(200, "获取个人详情异常");
		}
	}

	/**
	 * 获取项目所有赛程
	 *
	 * @param projectId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getScheduleByProject")
	public AjaxResult getScheduleByProject(String projectId, String groupId) {
		if (StringUtils.isEmpty(projectId)) {
			return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
		}
		CompetitionProject competitionProject = competitionProjectService.get(projectId);
		if(null == competitionProject || competitionProject.getDelFlag().equals("1")){
			return AjaxResult.error(PartyCode.IS_NO_DATA, "比赛项目不存在");
		}
		List<CompetitionSchedule> schedules = competitionScheduleService.list(new CompetitionSchedule(projectId));
		Map<String, Object> output = new HashMap<String, Object>();
		CompetitionProject project = competitionProjectService.get(projectId);
		if (project != null) {
			Map<String, Object> projectMap = new HashMap<String, Object>();
			projectMap.put("title", project.getTitle());
			projectMap.put("remarks", project.getRemarks());
			projectMap.put("picture", project.getPicture());
			projectMap.put("id", project.getId());

			output.put("project", projectMap);
		}

		if (StringUtils.isNotEmpty(groupId)) {
			CompetitionGroup group = competitionGroupService.get(groupId);
			Map<String, Object> groupMap = new HashMap<String,Object>();
			groupMap.put("groupName", group.getGroupName());
			groupMap.put("groupNo", group.getGroupNo());
			groupMap.put("id", group.getId());
			output.put("group", groupMap);
		}
		output.put("schedules", schedules);
		return AjaxResult.success(output);
	}

	/**
	 * 全部小组的成绩排行
	 *
	 * @param projectId
	 *            项目id
	 * @param scheduleId
	 *            日程id
	 * @param projectId
	 *            查询条件
	 * @param page
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getGroupRank")
	@VisitCollect(module = TargetType.COMPETITION)
	public AjaxResult getGroupRank(String projectId, String scheduleId, String groupName, Page page) {
		page.setLimit(20);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("projectId", projectId);
		params.put("scheduleId", scheduleId);
//		params.put("isComplete", "1");
		params.put("groupName", groupName);
		params.put("status", YesNoStatus.YES.getCode());
		List<Map<String, Object>> memberResults = competitionGroupResultService.getByGroup(params, page);
		competitionResultBizService.getGroupResultRank(memberResults, projectId, scheduleId);
		return AjaxResult.success(memberResults, page);
	}

	/**
	 * 全部人员的成绩排名
	 *
	 * @param rankInput 输入参数
	 * @param page
	 * @return
	 */
    @ResponseBody
    @RequestMapping("/getAllPersonRank")
	@VisitCollect(module = TargetType.COMPETITION)
    public AjaxResult getAllPersonRank(RankInput rankInput, Page page) {
        page.setLimit(20);
        // 项目下所有参赛人员
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("projectId", rankInput.getProjectId());
        params.put("scheduleId", rankInput.getScheduleId());
//        params.put("isComplete", "1");
        params.put("searchName", rankInput.getSearchName());
        params.put("sex", rankInput.getSex());
        params.put("groupId", rankInput.getGroupId());
        params.put("openStatus", YesNoStatus.YES.getCode());
        List<Map<String, Object>> memberResults = competitionResultService.getAllResult(params, page);
        competitionResultBizService.getMemberResultRank(memberResults, rankInput.getProjectId(), rankInput.getScheduleId());
        return AjaxResult.success(memberResults, page);
    }

    /**
     * 获取我的成绩
     *
     * @param rankInput 我的排名输入参数
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("/getMyRank")
    public AjaxResult getMyRank(RankInput rankInput, HttpServletRequest request) {
        // 项目下所有参赛人员
		CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        try {
            CompetitionMember competitionMember = competitionMemberService.findByProjectAndMember(currentUser.getId(), rankInput.getProjectId());
            if (competitionMember == null) {
                throw new BusinessException(100, "还没有参加该项目");
            }
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("projectId", rankInput.getProjectId());
            params.put("scheduleId", rankInput.getScheduleId());
//            params.put("isComplete", "1");
            params.put("searchName", rankInput.getSearchName());
            params.put("sex", rankInput.getSex());
            params.put("groupId", rankInput.getGroupId());
            params.put("openStatus", YesNoStatus.YES.getCode());
            params.put("memberId", currentUser.getId());
            List<Map<String, Object>> memberResults = competitionResultService.getAllResult(params, null);
            competitionResultBizService.getMemberResultRank(memberResults, rankInput.getProjectId(), rankInput.getScheduleId());
            if (memberResults.size() > 0) {
				return AjaxResult.success(memberResults.get(0));
			}
			Map<String,Object> map = Maps.newHashMap();
			return AjaxResult.success(map);
        } catch (BusinessException e) {
            return AjaxResult.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("获取我的成绩异常--memberId:" + currentUser.getId() + "；参数：" + JSONObject.toJSONString(rankInput), e);
            return AjaxResult.error(10000, "获取我的成绩异常");
        }
    }

	/**
	 * 获取我的小组成绩
	 *
	 * @param projectId  项目id
	 * @param scheduleId 赛程id
	 * @param request
	 * @return
	 */
	@ResponseBody
	@Authorization
	@RequestMapping("/getMyGroupRank")
	public AjaxResult getMyGroupRank(String projectId, String scheduleId, HttpServletRequest request) {
		try {
			CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
			if (currentUser == null) {
				throw new BusinessException(102, "用户不能为空");
			}
			CompetitionMember competitionMember = competitionMemberService.findByProjectAndMember(currentUser.getId(), projectId);
			if (competitionMember == null) {
				throw new BusinessException(100, "还没有参加该项目");
			}
			if (StringUtils.isEmpty(competitionMember.getGroupId())) {
				throw new BusinessException(101, "还没有参加小组");
			}
			Map<String, Object> params = Maps.newHashMap();
			params.put("projectId", projectId);
			params.put("scheduleId", scheduleId);
//			params.put("isComplete", "1");
			params.put("groupId", competitionMember.getGroupId());
            params.put("status", YesNoStatus.YES.getCode());
			List<Map<String, Object>> memberResults = competitionGroupResultService.getByGroup(params, null);
			competitionResultBizService.getGroupResultRank(memberResults, projectId, scheduleId);
			if (memberResults.size() > 0) {
				return AjaxResult.success(memberResults.get(0));
			} else {
				return AjaxResult.error(103, "该小组还没有录入成绩");
			}
		} catch (BusinessException e) {
			return AjaxResult.error(e.getCode(), e.getMessage());
		} catch (Exception e) {
            logger.error("获取我的小组成绩异常", e);
			return AjaxResult.error(10000, "获取我的小组成绩异常");
		}
	}

	/**
	 * 小组所有成员的成绩排行
	 *
	 * @param projectId
	 *            项目id
	 * @param groupId
	 *            小组id
	 * @param scheduleId
	 *            日程id
	 * @param searchName
	 *            查询条件
	 * @param page
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getGroupAllPersonalRank")
	public AjaxResult getGroupAllPersonalRank(String projectId, String groupId, String scheduleId, String searchName, Page page) {
		if (StringUtils.isEmpty(groupId)) {
			return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "小组id不能为空");
		}
		page.setLimit(20);
		// 项目下所有参赛人员
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("projectId", projectId);
		params.put("scheduleId", scheduleId);
		params.put("groupId", groupId);
//		params.put("isComplete", "1");
		params.put("searchName", searchName);
		List<Map<String, Object>> memberResults = competitionResultService.getGroupAllPersonResult(params, page);
		competitionResultBizService.getMemberResultRank(memberResults, projectId, scheduleId);
		return AjaxResult.success(memberResults, page);
	}

	/**
	 * 根据项目id获取小组
	 *
	 * @param projectId 项目id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getGroupByProject")
	public AjaxResult getGroupByProject(String projectId) {
		if (StringUtils.isEmpty(projectId)) {
			return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
		}
		CompetitionProject competitionProject = competitionProjectService.get(projectId);
		if (null == competitionProject || competitionProject.getDelFlag().equals("1")) {
			return AjaxResult.error(PartyCode.IS_NO_DATA, "比赛项目不存在");
		}
		List<CompetitionGroup> groups = competitionGroupService.list(new CompetitionGroup(projectId));
		for (CompetitionGroup group : groups) {
			group.setCreateDate(null);
			group.setCreateBy(null);
			group.setUpdateDate(null);
			group.setUpdateBy(null);
		}
		return AjaxResult.success(groups);
	}
}
